<?php

Yii::import('application.models._base.BaseClassBatch');

class ClassBatch extends BaseClassBatch {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public $maxPrice;
    public $minPrice;

    public function rules() {
        return array(
            array('price,seats, schedule_id, class_venue_id, start_date, end_date, start_time, end_time', 'required'),
        );
    }

    public static function findMinMaxPriceByClassbatch($classId) {
        $criteria = new CDbCriteria;
        $criteria->select = 'Min(price) as minPrice,Max(price) as maxPrice';
        $criteria->condition = 'classes_id=' . $classId;
        $classBatchPrice = ClassBatch::model()->find($criteria);
        if ($classBatchPrice['minPrice'] != $classBatchPrice['maxPrice']) {
            return 'Start From <img src="' . ThemePath(true) . '/images/rupees.png"> ' . number_format($classBatchPrice['minPrice'], 2) . ' - <img src="' . ThemePath(true) . '/images/rupees.png"> ' . number_format($classBatchPrice['maxPrice'], 2);
        } else {
            return 'Price <img src="' . ThemePath(true) . '/images/rupees.png"> ' . number_format($classBatchPrice['minPrice'], 2);
        }
    }

    public static function findMinMaxPriceByClassbatchForLearn($classId) {
        $criteria = new CDbCriteria;
        $criteria->select = 'Min(price) as minPrice,Max(price) as maxPrice';
        $criteria->condition = 'classes_id=' . $classId;
        $classBatchPrice = ClassBatch::model()->find($criteria);
        if ($classBatchPrice['minPrice'] != $classBatchPrice['maxPrice']) {
            return 'Start From <img src="' . ThemePath(true) . '/images/rupees.png"> ' . number_format($classBatchPrice['minPrice'], 2) . ' - <img src="' . ThemePath(true) . '/images/rupees.png"> ' . number_format($classBatchPrice['maxPrice'], 2);
        } else {
            return '<img src="' . ThemePath(true) . '/images/rupees.png"> ' . number_format($classBatchPrice['minPrice'], 2);
        }
    }

    public static function findMinMaxPriceByClassbatchforCategoryPage($classId) {
        $criteria = new CDbCriteria;
        $criteria->select = 'Min(price) as minPrice,Max(price) as maxPrice';
        $criteria->condition = 'classes_id=' . $classId;
        $classBatchPrice = ClassBatch::model()->find($criteria);
        if ($classBatchPrice['minPrice'] != $classBatchPrice['maxPrice']) {
            return number_format($classBatchPrice['minPrice'], 2) . ' -  ' . number_format($classBatchPrice['maxPrice'], 2);
        } else {
            return ' ' . number_format($classBatchPrice['minPrice'], 2);
        }
    }

    function getId() {
        return $this->id;
    }

    function getPrice() {
        return $this->price;
    }

    public static function getDiscountOnClass($couponCode, $batchPrice, $quantity, $batchId) {
        $couponModel = Coupons::model()->findByAttributes(array('name' => $couponCode, 'status' => SkillConfig::STATUS_ACTIVE));
        $earlyDscount = ClassBatch::getearlyDscountByBatch($batchId, $quantity);
        $groupDscountByBatch = ClassBatch::getgroupDscountByBatch($batchId, $quantity);
        $priceByCalsses = $quantity * $batchPrice;
        $total_amt = $priceByCalsses - ($earlyDscount + $groupDscountByBatch);
        if (!empty($couponModel)) {
            $price = $couponModel->inprice;
            $percentage = $couponModel->inpercentage;
            if ($price <> "") {
                $subtotalAfterDiscount = $total_amt - $price;
            }
            if ($percentage <> "") {
                $subtotalAfterDiscount = $total_amt - ($total_amt * ($percentage / 100));
            }
            return $subtotalAfterDiscount;
        }
    }

    public static function getChepeastPrice($chepeastBatchPrice, $quantity, $couponCode, $classId, $batchprice, $batchId) {
        if (($chepeastBatchPrice['classes_id'] == $classId) && ($chepeastBatchPrice['price'] == $batchprice)) {
            $discountBatchPrice = ClassBatch::getDiscountOnClass($couponCode, $batchprice, $quantity, $batchId);
            $afterDicountBatchPrice = $discountBatchPrice;         
            return $afterDicountBatchPrice;
        }
    }

    public static function getUpdatedprice($batcheid, $quantity) {
        $totalPrice = '';
        $currentDate = date('Y-m-d');
        $seats = $quantity;
        $batchData = ClassBatch::model()->find('id=:id', array(':id' => $batcheid));
        $price = $batchData->price * $seats;
        $price = $price;

        $earlyDiscountData = ClassEarlyDiscount::model()->findAllbyAttributes(array('class_batch_id' => $batcheid));
        if (count($earlyDiscountData) > 0) {
            foreach ($earlyDiscountData as $earlyDiscountData) {
                $valid_to = $earlyDiscountData->valid_to;
                $discount_price = $earlyDiscountData->discount_price;
                $in_percentage = $earlyDiscountData->in_percentage;
                if ($valid_to <> "" && $currentDate <= $valid_to) {
                    if (empty($discount_price) <> true) {
                        $totalPrice = $price - $discount_price;
                        break;
                        //$totalPrice = $totalPrice;
                    } elseif (empty($in_percentage) <> true) {

                        if ($totalPrice <> "") {
                            $in_percentage = $price * ($in_percentage / 100);
                            $totalPrice = $totalPrice - $in_percentage;
                            $totalPrice = $totalPrice;
                        } else {
                            $in_percentage = $price * ($in_percentage / 100);
                            $totalPrice = $price - $in_percentage;
                            $totalPrice = $totalPrice;
                        }
                    }
                }
            }
        } elseif ($totalPrice == '') {
            $totalPrice = $price;
            $totalPrice = $totalPrice;
        }

        /* Early Discout calculate */

        /* Group Discout calculate */
        $GroupDiscountData = GroupDiscount::model()->findAllbyAttributes(array('class_batch_id' => (int) $_POST['batchId']));

        if (count($GroupDiscountData) > 0) {
            foreach ($GroupDiscountData as $GroupDiscountData) {
                $group_size = $GroupDiscountData->group_size;
                $discount_amount = $GroupDiscountData->discount_amount;
                $discount_in_percentage = $GroupDiscountData->discount_in_percentage;

                if ($group_size <> "" && $group_size == $seats) {
                    if (empty($discount_amount) <> true) {
                        if ($totalPrice <> "") {
                            $totalPrice = $totalPrice - $discount_amount;
                        } else {
                            $totalPrice = $price - $discount_amount;
                        }
                        $totalPrice = $totalPrice;
                    } elseif (empty($discount_in_percentage) <> true) {
                        if ($totalPrice <> "") {
                            $in_percentage = $price * ($discount_in_percentage / 100);
                            $totalPrice = $totalPrice - $in_percentage;
                        } else {
                            $in_percentage = $price * ($discount_in_percentage / 100);
                            $totalPrice = $price - $in_percentage;
                            $totalPrice = $totalPrice;
                        }
                    }
                }
            }
        } elseif ($totalPrice == '') {
            $totalPrice = $price;
            $totalPrice = $totalPrice;
        }
        /* Group Discout calculate */

        return $totalPrice;
    }

    public static function getAllbatchByClass($classid, $venueId) {
        $date = date('Y-m-d');
        $batchArray = array();
        $weeklybatchArray = array();
        $allbatchData = array();
        $monthlybatchArray = array();
        $where = !empty($venueId) ? 't.class_venue_id=' . $venueId . ' AND t.classes_id=' . $classid : 't.classes_id=' . $classid;
        $command = Yii::app()->db->createCommand();
        $command->select('t.*,cwm.weekly_monthly_start_date');
        $command->from('skill_class_batch t LEFT JOIN skill_classbatchweelymonthly cwm ON (t.id = cwm.class_batch_id)');
        $command->where($where . ' AND  t.schedule_id=' . REPEAT_CLASS_MONTHLY . ' AND(cwm.weekly_monthly_start_date>=' . $date . ' OR t.start_date>=' . $date . ')');
        $monthlyClassData = $command->queryAll();
        foreach ($monthlyClassData as $batchData) {
            if (!empty($batchData['weekly_monthly_start_date'])) {
                $monthlybatchArray[] = array('id' => $batchData['id'], 'class_venue_id' => $batchData['class_venue_id'], 'start_date' => $batchData['weekly_monthly_start_date'], 'price' => $batchData['price'], 'seats' => $batchData['seats'], 'start_time' => $batchData['start_time'] . ' - ' . $batchData['end_time']);
            } else {
                $monthlybatchArray[] = array('id' => $batchData['id'], 'class_venue_id' => $batchData['class_venue_id'], 'start_date' => $batchData['start_date'], 'price' => $batchData['price'], 'seats' => $batchData['seats'], 'start_time' => $batchData['start_time'] . ' - ' . $batchData['end_time']);
            }
        }
        $batchArray = array_merge($batchArray, $monthlybatchArray);

        $weekelycommand = Yii::app()->db->createCommand();
        $weekelycommand->select('t.*,cwm.weekly_monthly_start_date');
        $weekelycommand->from('skill_class_batch t LEFT JOIN skill_classbatchweelymonthly cwm ON (t.id = cwm.class_batch_id)');
        $weekelycommand->where($where . ' AND  t.schedule_id=' . REPEAT_CLASS_WEEKLY . ' AND (cwm.weekly_monthly_start_date>=' . $date . ' OR t.start_date>=' . $date . ')');
        $weeklyClassData = $weekelycommand->queryAll();
        foreach ($weeklyClassData as $batchData) {
            if (!empty($batchData['weekly_monthly_start_date'])) {
                $weeklybatchArray[] = array('id' => $batchData['id'], 'class_venue_id' => $batchData['class_venue_id'], 'start_date' => $batchData['weekly_monthly_start_date'], 'price' => $batchData['price'], 'seats' => $batchData['seats'], 'start_time' => $batchData['start_time'] . ' - ' . $batchData['end_time']);
            } else {
                $weeklybatchArray[] = array('id' => $batchData['id'], 'class_venue_id' => $batchData['class_venue_id'], 'start_date' => $batchData['start_date'], 'price' => $batchData['price'], 'seats' => $batchData['seats'], 'start_time' => $batchData['start_time'] . ' - ' . $batchData['end_time']);
            }
        }
        $batchArray = array_merge($batchArray, $weeklybatchArray);

        $allbatchData = Yii::app()->db->createCommand();
        $allbatchData->select('t.*,cwm.date');
        $allbatchData->from('skill_class_batch t LEFT JOIN skill_batche_session cwm ON (t.id = cwm.batche_id)');
        $allbatchData->where($where . ' AND( t.schedule_id=' . CUSTOME_SESSION . ' OR t.schedule_id=' . NO_REPEAT . ') AND  (cwm.date>=' . $date . ' OR t.start_date>=' . $date . ')');
        $allbatchData = $allbatchData->queryAll();

        foreach ($allbatchData as $batchData) {
            if (!empty($batchData['date'])) {
                $allbatchData[] = array('id' => $batchData['id'], 'class_venue_id' => $batchData['class_venue_id'], 'start_date' => $batchData['date'], 'price' => $batchData['price'], 'seats' => $batchData['seats'], 'start_time' => $batchData['start_time'] . ' - ' . $batchData['end_time']);
            } else {
                $allbatchData[] = array('id' => $batchData['id'], 'class_venue_id' => $batchData['class_venue_id'], 'start_date' => $batchData['start_date'], 'price' => $batchData['price'], 'seats' => $batchData['seats'], 'start_time' => $batchData['start_time'] . ' - ' . $batchData['end_time']);
            }
        }
        $batchArray = array_merge($batchArray, $allbatchData);
        return $batchArray;
    }

    public static function classBatchstartDateList($batchArray) {
        $batchArraydata = array();
        $venueId = self::getvenueId($batchArray);
        foreach ($batchArray as $value) {
            if ($venueId == $value['class_venue_id']) {
                $batchArraydata[] = array('id' => $value['id'], 'start_date' => $value['start_date']);
            }
        }
        $venueDetails = CHtml::listData($batchArraydata, 'id', 'start_date');
        return $venueDetails;
    }

    public static function classBatchstartTimeList($batchArray) {
        $batchArraydata = array();
        $venueId = self::getvenueId($batchArray);
        foreach ($batchArray as $value) {
            if ($venueId == $value['class_venue_id']) {
                $batchArraydata[] = array('id' => $value['id'], 'start_time' => $value['start_time']);
            }
        }
        $venueDetails = CHtml::listData($batchArraydata, 'id', 'start_time');
        return $venueDetails;
    }

    private static function getvenueId($batchArray) {
        $venueId = '';
        $i = 1;
        foreach ($batchArray as $value) {
            if ($i == 1) {
                $venueId = $value['class_venue_id'];
            }
            break;
            ;
        }
        return $venueId;
        ;
    }

    public static function getVenueListBox($batchArray) {
        $batchArraydata = array();
        foreach ($batchArray as $value) {
            $venuename = ClassVenue::model()->findByPk($value['class_venue_id']);
            $batchArraydata[] = array('id' => $venuename->id, 'name' => $venuename->name);
        }
        $venueDetails = CHtml::listData($batchArraydata, 'id', 'name');
        return $venueDetails;
    }

    public static function classBatchseatsList($batchArray) {
        $batchArraydata = array();
        $venueId = self::getvenueId($batchArray);
        $seats = '';
        foreach ($batchArray as $value) {
            if ($venueId == $value['class_venue_id']) {
                $seats = $value['seats'];
            }
            break;
        }
        for ($i = 1; $i <= $seats; $i++) {
            $batchArraydata[] = array('id' => $i, 'name' => $i);
        }
        $venueDetails = CHtml::listData($batchArraydata, 'id', 'name');
        return $venueDetails;
    }

    public static function getbatchIdonviewDeatls($batchArray) {
        $batchArraydata = array();
        $batchId = '';
        $venueId = self::getvenueId($batchArray);
        foreach ($batchArray as $value) {
            if ($venueId == $value['class_venue_id']) {
                $batchId = $value['id'];
            }
            break;
        }
        return $batchId;
    }

    public static function getBatchPriceBySeats($batchId, $seats) {
        $prevousPrice = '';
        $totalPrice = '';
        $currentDate = date('Y-m-d');
        $batchData = ClassBatch::model()->find('id=:id', array(':id' => (int) $batchId));
        if (!empty($batchData)) {
            $batchPrice = $batchData->price;
            $price = $batchData->price * $seats;
            echo "Subtotal Rs. " . $price . '<br>';
            $earlyDiscount = ClassEarlyDiscount::model()->find('class_batch_id=' . (int) $batchId, ' AND valid_to>=' . $currentDate . 'ORDER BY  valid_to ASC ');
            if (!empty($earlyDiscount))
                if (!empty($earlyDiscount->discount_price)) {
                    echo "Early Discount Rs. " . $earlyDiscount->discount_price * $seats . '<br>';
                    $totalPrice = $price - $earlyDiscount->discount_price * $seats;
                } else {
                    $in_percentage = $price * ($earlyDiscount->in_percentage / 100);
                    echo "Early Discount Rs. " . $in_percentage . '<br>';
                    $totalPrice = $price - $in_percentage;
                }
            $GroupDiscountData = GroupDiscount::model()->findbyAttributes(array('class_batch_id' => (int) $batchId));
            if (!empty($GroupDiscountData)) {
                $discount_amount = $GroupDiscountData->discount_amount;
                $discount_in_percentage = $GroupDiscountData->discount_in_percentage;
                if ($GroupDiscountData->group_size <= $seats)
                    if (!empty($GroupDiscountData->discount_amount)) {
                        echo "Group Discount Rs. " . $discount_amount . '<br>';
                        $totalPrice = (!empty($totalPrice)) ? $totalPrice - $discount_amount : $price - $discount_amount;
                    } else {
                        $in_percentage = $batchPrice * ($discount_in_percentage / 100);
                        echo "Group Discount Rs. " . $in_percentage . '<br>';
                        $totalPrice = (!empty($totalPrice)) ? $totalPrice - $in_percentage : $price - $in_percentage;
                    }
            }
            $totalPrice = (!empty($totalPrice)) ? $totalPrice : $price;
            echo '<input name="ShoppingCart[amount]" id="totalPriceId" type="hidden" value="' . $totalPrice . '" />';
            echo '<div class="grand_total borB rempaddingB"></div>';
            echo "Grand Total Rs. " . $totalPrice;
        }
    }

    public static function getearlyDscountByBatch($batchId, $seats) {
        $currentDate = date('Y-m-d');
        $earlyPrice = '';
        $batchData = ClassBatch::model()->find('id=:id', array(':id' => (int) $batchId));
        if (!empty($batchData)) {
            $batchPrice = $batchData->price;
            $price = $batchData->price * $seats;
            $earlyDiscount = ClassEarlyDiscount::model()->find('class_batch_id=' . (int) $batchId, ' AND valid_to>=' . $currentDate . 'ORDER BY  valid_to ASC ');
            if (!empty($earlyDiscount)) {
                if (!empty($earlyDiscount->discount_price)) {
                    $$earlyPrice = $earlyDiscount->discount_price * $seats;
                } else {
                    $earlyPrice = $price * ($earlyDiscount->in_percentage / 100);
                }
            }
            return $earlyPrice;
        }
    }

    public static function getgroupDscountByBatch($batchId, $seats) {
        $currentDate = date('Y-m-d');
        $groupPrice = '';
        $batchData = ClassBatch::model()->find('id=:id', array(':id' => (int) $batchId));
        if (!empty($batchData)) {
            $batchPrice = $batchData->price;
            $price = $batchData->price * $seats;
            $GroupDiscountData = GroupDiscount::model()->findbyAttributes(array('class_batch_id' => (int) $batchId));
            if (!empty($GroupDiscountData)) {
                $discount_amount = $GroupDiscountData->discount_amount;
                $discount_in_percentage = $GroupDiscountData->discount_in_percentage;
                if ($GroupDiscountData->group_size <= $seats)
                    if (!empty($GroupDiscountData->discount_amount)) {
                        $groupPrice = $discount_amount;
                    } else {
                        $groupPrice = $batchPrice * ($discount_in_percentage / 100);
                    }
            }
            return $groupPrice;
        }
    }

    public static function getBatchPriceBySeatsInt($batchId, $seats, $type) {
        $prevousPrice = '';
        $checkoutPrice = '';
        $totalPrice = '';
        $discountapplied = '';
        $currentDate = date('Y-m-d');
        $batchData = ClassBatch::model()->find('id=:id', array(':id' => (int) $batchId));
        if (!empty($batchData)) {
            $batchPrice = $batchData->price;
            $price = $batchData->price * $seats;
            $prevousPrice = "Subtotal Rs. " . $price . '<br>';
            $earlyDiscount = ClassEarlyDiscount::model()->find('class_batch_id=' . (int) $batchId, ' AND valid_to>=' . $currentDate . 'ORDER BY  valid_to ASC ');
            if (!empty($earlyDiscount))
                if (!empty($earlyDiscount->discount_price)) {
                    if ($type <> "int" && $type <> "checkout")
                        echo "Early Discount Rs. " . $earlyDiscount->discount_price * $seats . '<br>';
                    $checkoutPrice.= "Early Discount Rs. " . $earlyDiscount->discount_price * $seats . '<br>';
                    $totalPrice = $price - $earlyDiscount->discount_price * $seats;
                    $discountapplied = 1;
                } else {
                    $in_percentage = $price * ($earlyDiscount->in_percentage / 100);
                    if ($type <> "int" && $type <> "checkout")
                        echo "Early Discount Rs. " . $in_percentage . '<br>';
                    $checkoutPrice.= "Early Discount Rs. " . $in_percentage . '<br>';
                    $totalPrice = $price - $in_percentage;
                    $discountapplied = 1;
                }
            $GroupDiscountData = GroupDiscount::model()->findbyAttributes(array('class_batch_id' => (int) $batchId));
            if (!empty($GroupDiscountData)) {
                $discount_amount = $GroupDiscountData->discount_amount;
                $discount_in_percentage = $GroupDiscountData->discount_in_percentage;
                if ($GroupDiscountData->group_size <= $seats)
                    if (!empty($GroupDiscountData->discount_amount)) {
                        if ($type <> "int" && $type <> "checkout")
                            echo "Group Discount Rs. " . $discount_amount . '<br>';
                        $checkoutPrice.= "Group Discount Rs. " . $discount_amount . '<br>';
                        $totalPrice = (!empty($totalPrice)) ? $totalPrice - $discount_amount : $price - $discount_amount;
                        $discountapplied = 1;
                    } else {
                        $in_percentage = $batchPrice * ($discount_in_percentage / 100);
                        if ($type <> "int" && $type <> "checkout")
                            echo "Group Discount Rs. " . $in_percentage . '<br>';
                        $checkoutPrice.= "Group Discount Rs. " . $in_percentage . '<br>';
                        $totalPrice = (!empty($totalPrice)) ? $totalPrice - $in_percentage : $price - $in_percentage;
                        $discountapplied = 1;
                    }
            }


            if ($type == "int") {
                $returdata = $totalPrice = (!empty($totalPrice)) ? $totalPrice : $price;
            } elseif ($type == "txt" && $discountapplied == 1) {
                echo $prevousPrice;
                $returdata = $prevousPrice;
            } elseif ($type == "txt" && $discountapplied == 0) {
                $returdata = '';
            } elseif ($type == "checkout" && $discountapplied == 1) {
                $returdata = $prevousPrice . $checkoutPrice;
            } elseif ($type == "checkout" && $discountapplied == 0) {
                $returdata = $prevousPrice;
            }
        }

        return $returdata;
    }

    public static function getBatchPricebyBatchId($batchId) {
        $batchPrice = ClassBatch::model()->findByPk($batchId);
        return !empty($batchPrice) ? $batchPrice->price : '';
    }

}